// adjust 自定义事件
import { Adjust, AdjustConfig, AdjustEvent } from 'react-native-adjust';

import { getStorageItem, storage } from '@utils/storage.ts';

import { isShowTestURL } from './http';
import { ADJUST_APP_TOKEN, APP_NAME, DEVICE_ID } from '@/constants';

export const AdjustEventsUtil = {
  config() {
    // 联网后，初始化Adjust
    // AdjustConfig.EnvironmentSandbox沙箱环境用于测试；
    // AdjustConfig.EnvironmentProduction生产环境；
    // 如果接入的测试环境后端服务，默认是沙箱环境，否则是生产环境
    const adjustConfig = new AdjustConfig(
      ADJUST_APP_TOKEN,
      isShowTestURL ? AdjustConfig.EnvironmentSandbox : AdjustConfig.EnvironmentProduction,
    );

    // 设置日志级别
    adjustConfig.setLogLevel(AdjustConfig.LogLevelVerbose);
    // 设置设备ID，避免重复记录为多次新安装
    adjustConfig.setExternalDeviceId(getStorageItem(DEVICE_ID) || 'none-device-id');
    // 开启后台记录
    adjustConfig.setSendInBackground(true);

    Adjust.create(adjustConfig);
  },

  // 点下了订阅页的订阅按钮（点击按钮则触发，并非支付成功才上报）
  checkout() {
    const adjustEvent = new AdjustEvent('85zb6e');
    Adjust.trackEvent(adjustEvent);
  },
  // 应用首次打开，用户首次登录成功后触发，只上报一次，用于与CPI数据进行对比，看安装到打开应用的转换率
  first_load() {
    const adjustEvent = new AdjustEvent('cblc7f');
    if (!storage.getBoolean(`${APP_NAME}_first_load`)) {
      Adjust.trackEvent(adjustEvent);
    } else {
      storage.set(`${APP_NAME}_first_load`, true);
    }
  },
  // 点击永久付费，并且支付成功后触发
  purchase_lifetime(price?: number, currency?: string) {
    const adjustEvent = new AdjustEvent('i0fuqy');
    // 记录事件收入
    adjustEvent.setRevenue(price || 49.99, currency || 'USD');
    Adjust.trackEvent(adjustEvent);
  },
  // 点击按周订阅，并且支付成功后触发
  purchase_weekly(price?: number, currency?: string) {
    const adjustEvent = new AdjustEvent('6g5q9t');
    adjustEvent.setRevenue(price || 4.99, currency || 'USD');
    Adjust.trackEvent(adjustEvent);
  },
  // 点击按年订阅，并且支付成功后触发
  purchase_yearly(price?: number, currency?: string) {
    const adjustEvent = new AdjustEvent('zdkfck');
    adjustEvent.setRevenue(price || 39.99, currency || 'USD');
    Adjust.trackEvent(adjustEvent);
  },
};
